package cn.lichenfei.fxui.controls;

import cn.lichenfei.fxui.common.FxUtil;
import cn.lichenfei.fxui.common.Level;
import cn.lichenfei.fxui.controls.skins.CFAlertSkin;
import javafx.animation.FadeTransition;
import javafx.beans.property.*;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Control;
import javafx.scene.control.Skin;
import javafx.scene.input.MouseEvent;
import javafx.util.Duration;

public class CFAlert extends Control {

    private static final String STYLE_SHEET = FxUtil.getResource("/css/cf-alert.css");
    private static final String STYLE_CLASS = "cf-alert";
    //
    private final StringProperty text = new SimpleStringProperty();
    private final ObjectProperty<Level> level = new SimpleObjectProperty<>(Level.PRIMARY);
    private final ObjectProperty<EventHandler<? super MouseEvent>> hideEvent = new SimpleObjectProperty<>();
    private final BooleanProperty closable = new SimpleBooleanProperty(false);

    public CFAlert(String text) {
        initialize();
        this.text.set(text);
    }

    public CFAlert(String text, Level level) {
        initialize();
        this.text.set(text);
        this.level.set(level);
    }

    public CFAlert(String text, Level level, boolean closable) {
        initialize();
        this.text.set(text);
        this.level.set(level);
        this.closable.set(closable);
    }

    public String getText() {
        return text.get();
    }

    public StringProperty textProperty() {
        return text;
    }

    public void setLevel(Level level) {
        this.level.set(level);
    }

    public Level getLevel() {
        return level.get();
    }

    public ObjectProperty<Level> levelProperty() {
        return level;
    }

    public BooleanProperty closableProperty() {
        return closable;
    }

    public EventHandler<? super MouseEvent> getHideEvent() {
        return hideEvent.get();
    }

    private static final FadeTransition FT = new FadeTransition(Duration.millis(250));

    public void setHideEvent(EventHandler<? super MouseEvent> hideEvent) {
        this.hideEvent.set(hideEvent);
    }

    public static void hide(Node node){
        FT.setNode(node);
        FT.setFromValue(1);
        FT.setToValue(0);
        FT.play();
        FT.setOnFinished(event -> {
            node.setManaged(false);
            node.setVisible(false);
        });
    }

    protected void initialize() {
        setMaxSize(USE_COMPUTED_SIZE, USE_PREF_SIZE);
        getStyleClass().add(STYLE_CLASS);
        // 更新class
        levelProperty().addListener((observable, oldValue, newValue) -> newValue.resetStyleClass(this));
    }

    @Override
    protected Skin<?> createDefaultSkin() {
        return new CFAlertSkin(this);
    }

    @Override
    public String getUserAgentStylesheet() {
        return STYLE_SHEET;
    }

}
